import 'package:flutter/material.dart';
import '../models/customer.dart';

class CustomersSection extends StatefulWidget {
  const CustomersSection({Key? key}) : super(key: key);

  @override
  State<CustomersSection> createState() => _CustomersSectionState();
}

class _CustomersSectionState extends State<CustomersSection> {
  final TextEditingController _searchController = TextEditingController();
  List<Customer> _filteredCustomers = [];

  // ۋاقىتلىق خېرىدارلار تىزىملىكى (كېيىن مەلۇمات ئامبىرىدىن ئېلىنىدۇ)
  final List<Customer> _customers = [
    Customer(
      id: 'C001',
      name: 'ئابدۇللا',
      phone: '13799990000',
      address: 'ئۈرۈمچى شەھىرى',
      totalPurchases: 35.95,
      purchaseCount: 2,
      lastPurchase: DateTime.now().subtract(const Duration(hours: 2)),
      notes: 'داۋاملىق كېلىدىغان خېرىدار',
    ),
    Customer(
      id: 'C002',
      name: 'مەمەت',
      phone: '13788880000',
      address: 'ئۈرۈمچى شەھىرى',
      totalPurchases: 19.95,
      purchaseCount: 1,
      lastPurchase: DateTime.now().subtract(const Duration(days: 1)),
      notes: '',
    ),
  ];

  @override
  void initState() {
    super.initState();
    _filteredCustomers = _customers;
    _searchController.addListener(_filterCustomers);
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  void _filterCustomers() {
    final query = _searchController.text.toLowerCase();
    setState(() {
      _filteredCustomers = _customers.where((customer) {
        return customer.name.toLowerCase().contains(query) ||
               customer.phone.contains(query) ||
               customer.id.toLowerCase().contains(query);
      }).toList();
    });
  }

  void _showAddEditCustomerDialog([Customer? customer]) {
    final isEditing = customer != null;
    final nameController = TextEditingController(text: customer?.name ?? '');
    final phoneController = TextEditingController(text: customer?.phone ?? '');
    final addressController = TextEditingController(text: customer?.address ?? '');
    final notesController = TextEditingController(text: customer?.notes ?? '');

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(isEditing ? 'خېرىدار ئۇچۇرىنى تەھرىرلەش' : 'يېڭى خېرىدار قوشۇش'),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: nameController,
                decoration: const InputDecoration(
                  labelText: 'ئىسمى',
                  icon: Icon(Icons.person),
                ),
              ),
              const SizedBox(height: 16),
              TextField(
                controller: phoneController,
                decoration: const InputDecoration(
                  labelText: 'تېلېفون نومۇرى',
                  icon: Icon(Icons.phone),
                ),
                keyboardType: TextInputType.phone,
              ),
              const SizedBox(height: 16),
              TextField(
                controller: addressController,
                decoration: const InputDecoration(
                  labelText: 'ئادرېس',
                  icon: Icon(Icons.location_on),
                ),
                maxLines: 2,
              ),
              const SizedBox(height: 16),
              TextField(
                controller: notesController,
                decoration: const InputDecoration(
                  labelText: 'ئىزاھات',
                  icon: Icon(Icons.note),
                ),
                maxLines: 3,
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('ۋاز كەچ'),
          ),
          ElevatedButton(
            onPressed: () {
              // يېڭى خېرىدار قوشۇش ياكى مەۋجۇت خېرىدارنى يېڭىلاش
              if (isEditing) {
                final index = _customers.indexWhere((c) => c.id == customer.id);
                if (index != -1) {
                  setState(() {
                    _customers[index] = Customer(
                      id: customer.id,
                      name: nameController.text,
                      phone: phoneController.text,
                      address: addressController.text,
                      notes: notesController.text,
                      totalPurchases: customer.totalPurchases,
                      purchaseCount: customer.purchaseCount,
                      lastPurchase: customer.lastPurchase,
                    );
                    _filterCustomers();
                  });
                }
              } else {
                setState(() {
                  _customers.add(Customer(
                    id: 'C${(_customers.length + 1).toString().padLeft(3, '0')}',
                    name: nameController.text,
                    phone: phoneController.text,
                    address: addressController.text,
                    notes: notesController.text,
                    totalPurchases: 0,
                    purchaseCount: 0,
                    lastPurchase: DateTime.now(),
                  ));
                  _filterCustomers();
                });
              }
              Navigator.pop(context);
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.orange,
            ),
            child: Text(isEditing ? 'ساقلاش' : 'قوشۇش'),
          ),
        ],
      ),
    );
  }

  void _showCustomerDetails(Customer customer) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('${customer.name} - تەپسىلاتى'),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildDetailRow('خېرىدار نومۇرى:', customer.id),
              _buildDetailRow('تېلېفون:', customer.phone),
              _buildDetailRow('ئادرېس:', customer.address),
              const Divider(),
              _buildDetailRow(
                'جەمئىي سېتىۋالغان سوممىسى:',
                '¥${customer.totalPurchases.toStringAsFixed(2)}',
                isHighlighted: true,
              ),
              _buildDetailRow(
                'سودا قېتىم سانى:',
                customer.purchaseCount.toString(),
              ),
              _buildDetailRow(
                'ئەڭ ئاخىرقى سودا:',
                _formatDate(customer.lastPurchase),
              ),
              if (customer.notes.isNotEmpty) ...[
                const Divider(),
                const Text(
                  'ئىزاھات:',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                Text(customer.notes),
              ],
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('تامام'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              _showAddEditCustomerDialog(customer);
            },
            child: const Text('تەھرىرلەش'),
          ),
        ],
      ),
    );
  }

  Widget _buildDetailRow(String label, String value, {bool isHighlighted = false}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            label,
            style: const TextStyle(fontWeight: FontWeight.bold),
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              value,
              style: TextStyle(
                color: isHighlighted ? Colors.orange : null,
                fontWeight: isHighlighted ? FontWeight.bold : null,
              ),
            ),
          ),
        ],
      ),
    );
  }

  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} '
           '${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: TextField(
                  controller: _searchController,
                  decoration: InputDecoration(
                    hintText: 'خېرىدار ئىزدەش...',
                    prefixIcon: const Icon(Icons.search),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 16),
              ElevatedButton.icon(
                onPressed: () => _showAddEditCustomerDialog(),
                icon: const Icon(Icons.add),
                label: const Text('يېڭى خېرىدار'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.orange,
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          
          Expanded(
            child: Card(
              child: ListView.builder(
                itemCount: _filteredCustomers.length,
                itemBuilder: (context, index) {
                  final customer = _filteredCustomers[index];
                  return ListTile(
                    leading: CircleAvatar(
                      backgroundColor: Colors.orange.shade100,
                      child: Text(
                        customer.name.characters.first,
                        style: TextStyle(
                          color: Colors.orange.shade900,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    title: Text(customer.name),
                    subtitle: Text('${customer.phone}\n'
                        'جەمئىي سودا: ¥${customer.totalPurchases.toStringAsFixed(2)}'),
                    isThreeLine: true,
                    trailing: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        IconButton(
                          icon: const Icon(Icons.edit),
                          onPressed: () => _showAddEditCustomerDialog(customer),
                          color: Colors.blue,
                        ),
                        IconButton(
                          icon: const Icon(Icons.visibility),
                          onPressed: () => _showCustomerDetails(customer),
                          color: Colors.green,
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
} 